// page_two/guanlzd/guanlzd.js
let app = getApp()
let yuming = app.globalData.yuming
var shuzong = []
var shu = []
const request = require('../../config/request');
Page({
  ...request,
  /**
   * 页面的初始数据
   */
  data: {
    yuming: yuming,
    heights: "",
    title: '药政学习',
    huan: ['承诺书', '管理制度', '学习考试'],
    currtab: 0,
    canvasHidden: true,
    ratio: 0, // 根据尺寸动态计算 1px换算成多少rpx
    windowWidth: 0, // 可使用窗口宽度
    windowHeight: 0, // 可使用窗口高度
    xiazai: false,
    canvasW: 350, //canvas宽
    canvasH: 574, //canvas高
    aaa: 1,
    qming: '',
    qqqm: false,
    foodsafetyImg: '', //生成之后的承诺书
    glzdList: [],
    ksxz: '',
    tiku: [],
    tiindex: 0,
    select: '',
    correct: '',
    error: '',
    buttonjz: false,
    isChoose: -1,
    isKaoshi: false,
    finish: true,
    page: 1,
    gongwu: false,
    is_shang: false, //是否点击了上一题
    xunzti:[]
  },

  // tab切换
  qies(e) {
    shuzong = []
    shu = []
    var index = e.currentTarget.dataset.currtab
    this.setData({
      currtab: index,
      page: 1,
      isKaoshi: false,
      finish: false,
      tiindex: 0,
      buttonjz: false,
      gongwu: false
    })
    if (this.data.currtab == 0) {
      this.chengns();
    }
    if (this.data.currtab == 1) {
      this.getGlzdList();
    }
    if (this.data.currtab == 2) {
      this.getDtxy();
    }
  },
  getGlzdList() {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'none'
    })
    this.myRequest(yuming + 'Yiyao/YiyaoArticle', {
      page: that.data.page
    }, "POST").then(res => {
      if (res.data.code == 200) {
        wx.hideLoading()
        shu = res.data.data;
        if (that.data.page != 1) {
          if (shu.length != 10) {
            that.setData({
              gongwu: true
            })
          }
        }
        that.setData({
          glzdList: shuzong.concat(shu)
        })
      }
    })
  },
  getDtxy() {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'none'
    })
    this.myRequest(yuming + 'Besall/thatHomeAgreement', {
      place: 'yyxxksxz'
    }, "POST").then(res => {
      wx.hideLoading()
      if (res.data.code == 200) {
        this.setData({
          ksxz: res.data.data
        })
        console.log(res.data.data)
      }
    })
  },
  // 进入详情
  xq(e) {
    var id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/page_two/glzdxq/glzdxq?id=' + id,
    })
  },
  // 查看更多
  lookmore() {
    shuzong = this.data.glzdList
    this.setData({
      page: (this.data.page) + 1
    })
    this.getGlzdList()
  },
  // 答题
  btnOpClick: function (e) {
    var type = e.currentTarget.dataset.type
    var index = e.currentTarget.dataset.index
    var id = e.currentTarget.dataset.id
    var select = e.currentTarget.id;
    var tiku = this.data.tiku
    var indexs = this.data.tiindex
    this.setData({
      isChoose: e.currentTarget.dataset.index,
      titype: type,
      tiku: tiku
    })
    if (type == 2) {
      tiku[indexs].aswers[index].is_true = !tiku[indexs].aswers[index].is_true
      // 多选
      this.data.xzState[e.currentTarget.dataset.index] = !(this.data.xzState[e.currentTarget.dataset.index])
      this.setData({
        xzState: this.data.xzState
      })
      console.log(this.data.xzState)
      var value = ''
      // for (let i = 0; i < this.data.xzState.length; i++) {
      //   if (this.data.xzState[i] == true) {
      //     value += this.data.tiku[this.data.tiindex].aswers[i].ident + ','
      //   }
      // }
      tiku[indexs].aswers.forEach((item,indexa)=>{
        console.log(tiku[indexs].aswers[indexa])
        if(tiku[indexs].aswers[indexa].is_true == true){
          value += tiku[indexs].aswers[indexa].ident + ','
        }
      })
      tiku[indexs].huida = value.substring(0, value.lastIndexOf(','))
      console.log(value)
      this.setData({
        select: value.substring(0, value.lastIndexOf(',')),
        tiku: tiku
      })
      // console.log(this.data.select)
    } else {
      tiku[indexs].aswers.forEach((item, indexa) => {
        if (tiku[indexs].aswers[indexa].id == id) {
          tiku[indexs].aswers[indexa].is_true = true
        } else {
          tiku[indexs].aswers[indexa].is_true = false
        }
      })
      tiku[indexs].huida =  tiku[indexs].aswers[index].ident
      this.setData({
        select: tiku[indexs].aswers[index].ident,
        tiku: tiku
      })
    }
  },
  // 上一题
  lastQuestion: function () {
    this.setData({
      tiindex: this.data.tiindex - 1
    });
    console.log(77987878)
    console.log(this.data.tiku)
    console.log(this.data.tiku[this.data.tiindex])
    console.log(this.data.tiku[this.data.tiindex].huida)
    this.setData({
      is_shang: true,
      select: this.data.tiku[this.data.tiindex].huida,
      tiku:this.data.tiku
    })
    // if (this.data.tiindex == 0) {
    //   wx.showToast({
    //     title: '没有上一题了唷',
    //   })
    // }
    // if (this.data.tiindex < this.data.tiku.length) {
     
    // }
    // this.setData({
    //   select: this.data.select
    // })
  },
  // 下一题
  nextQuestion: function () {
    var that = this;
    that.setData({
      is_shang: false
    })
    if (that.data.select == '') {
      wx.showToast({
        title: '您还没有选择哦！',
        icon: 'none'
      })
    } else {
      let yes = this.data.tiku[this.data.tiindex].yes
      console.log(yes)
      if (this.data.select == yes) {
        this.setData({
          correct: this.data.correct + '|' + this.data.tiku[this.data.tiindex].id
        })
        console.log(this.data.correct)
      } else {
        this.setData({
          error: this.data.error + '|' + this.data.tiku[this.data.tiindex].id
        })
        console.log(this.data.error)
      }
      this.setState();
      that.setData({
        select: '',
        isChoose: -1
      })
      if (that.data.tiindex < that.data.tiku.length) {
        this.setData({
          tiindex: that.data.tiindex + 1
        });
      }
      if (that.data.tiindex == that.data.tiku.length) {
        this.Endanswer()
      }
    }
  },
  Endanswer() {
    wx.showLoading({
      title: '加载中',
      icon: 'none'
    })
    var that = this;
    that.setData({
      correct: that.data.correct.substr(1),
      error: that.data.error.substr(1),
      buttonjz: true,
      finish: true,
    })
    this.myRequest(yuming + 'Yiyao/YiyaoQuestionEnd', {
      id: that.data.tikuid,
      correct: that.data.correct,
      error: that.data.error,
      shopId: wx.getStorageSync('shopId')
    }, "POST").then(res => {
      wx.hideLoading()
      if (res.data.code == 200) {
        this.setData({
          answerRes: res.data.data
        })
      }
    })
  },
  lsdtjl() {
    wx.navigateTo({
      url: '/page_two/lsdtjl/lsdtjl',
    })
  },
  agree() {
    this.setData({
      isKaoshi: true
    })
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'none'
    })
    this.myRequest(yuming + 'Yiyao/YiyaoQuestionStar', {
      shopId: wx.getStorageSync('shopId')
    }, "POST").then(res => {
      wx.hideLoading()
      if (res.data.code == 200) {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
        this.setData({
          tiku: res.data.single,
          tikuid: res.data.id
        })
        this.setState();
      } else if (res.data.code == 201) {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },
  // 设置多选题false数组
  setState() {
    let xzState = []
    for (let i = 0; i < this.data.tiku[this.data.tiindex].aswers.length; i++) {
      xzState.push(false)
    }
    this.setData({
      xzState: xzState
    })
  },
  disagree() {
    this.setData({
      currtab: 1
    })
    this.getGlzdList();
  },

  // 没有签名时打开签名
  qianmi() {
    this.setData({
      qqqm: !this.data.qqqm
    })
    if (!this.data.qqqm) {
      this.chengns()
    }
  },
  // 修改签名
  xiugaiqm() {
    this.setData({
      qqqm: !this.data.qqqm,
      isshw: true
    })
    this.chengns()
  },


  backs() {
    wx.navigateBack({
      delta: 0
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.setData({
      heights: wx.getMenuButtonBoundingClientRect().top + 5,
      title: options.title,
      currtab: options.curr
    })
    // 签名
    const context = wx.createCanvasContext('firstCanvas');
    context.setFillStyle('#fff')
    context.fillRect(0, 0, 500, 150)
    this.setData({
      context
    });
    context.draw()
    // 获取承诺数
    this.chengns()
  },
  downLoad: function (e) {
    var that = this;
    wx.showLoading({
      title: '正在生成图片',
    })
    // 背景 承诺书
    wx.downloadFile({
      url: that.data.cns,
      success: function (res3) {
        that.setData({
          cnss: res3.tempFilePath
        })
        // 签名
        if (that.data.qming != '') {
          console.log(121111111111)
          wx.downloadFile({
            url: that.data.qming,
            success: function (res3) {
              that.setData({
                qian: res3.tempFilePath
              })
              that.createCanvasShareImage();
            }
          })
        } else {
          console.log(3333333333333)
          that.createCanvasShareImage();
        }
      }
    })
  },
  // 绘制
  createCanvasShareImage: function () {
    let context = wx.createCanvasContext('shareCanvas' + this.data.aaa);
    let canvasWidthPx = 700 / this.data.ratio;
    var windowWidth = this.data.windowWidth //手机宽
    var windowHeight = this.data.windowHeight //手机搞
    // x轴
    var pagex = 80
    var pagey = 240
    // canvas背景色
    context.fillStyle = '#fff';
    context.fillRect(0, 0, this.data.canvasW, this.data.canvasH);
    // 承诺书
    context.drawImage(this.data.cnss, 0, 0, this.data.canvasW, this.data.canvasH);
    // 店铺名
    context.fillStyle = '#000';
    context.setFontSize(16);
    context.fillText(this.data.dianpu, 50, 55);
    // 时间
    context.fillStyle = '#000';
    context.setFontSize(13);
    context.fillText(this.data.shijian, this.data.canvasW - 100, this.data.canvasH - 25);
    //签名
    if (this.data.qming != '') {
      context.drawImage(this.data.qian, this.data.canvasW - 95, this.data.canvasH - 80, 90, 45);
    }
    context.draw();
    wx.hideLoading({})
    // this.setData({
    //   xiazai: true
    // })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    wx.getSystemInfo({
      success: res => {
        // console.log(res);
        this.setData({
          windowWidth: res.windowWidth * 1.5,
          windowHeight: res.windowHeight,
        });
        this.setData({
          // 屏幕宽度 375px = 750rpx，1px=2rpx
          // 1px = （750 / 屏幕宽度）rpx；
          // 1rpx = （屏幕宽度 / 750）px;
          ratio: 750 / this.data.windowWidth
        });
      }
    });
  },
  // 签名
  bindtouchstart: function (e) {
    this.data.context.moveTo(e.changedTouches[0].x, e.changedTouches[0].y);
  },
  clear: function () {
    this.data.context.draw();
    this.data.context.setFillStyle('#fff')
    this.data.context.fillRect(0, 0, 500, 150)
  },
  bindtouchmove: function (e) {
    // console.log(e.changedTouches)
    this.data.context.lineTo(e.changedTouches[0].x, e.changedTouches[0].y);
    this.data.context.stroke();
    this.data.context.draw(true);
    this.data.context.moveTo(e.changedTouches[0].x, e.changedTouches[0].y);
  },
  export: function () {
    let that = this;
    that.data.context.draw(true, wx.canvasToTempFilePath({
      fileType: 'png',
      canvasId: 'firstCanvas',
      success(res) {
        console.log(222)
        let {
          tempFilePath
        } = res;
        console.log(tempFilePath)
        wx.uploadFile({
          url: yuming + 'Besall/Upload',
          filePath: tempFilePath,
          name: 'file',
          formData: {

          },
          success(res) {
            console.log(333)
            var data = JSON.parse(res.data)
            var qianming = data.httpUrl + data.imgUrl
            wx.setStorageSync('sign', qianming);
            // wx.showToast({
            //   title: '签名成功',
            //   icon: 'none'
            // })
            that.setData({
              qqqm: false,
            })
            that.chengns()
            setTimeout(function () {
              that.shengcnuoshu()
            }, 1000)
          }
        })
      },
      fail() {
        wx.showToast({
          title: '导出失败',
          icon: 'none',
          duration: 2000
        })
      }
    }))
  },
  // 获取承诺书
  chengns() {
    var that = this
    this.myRequest(yuming + 'Besall/backFoodSafetyBgimg', {
      shopId: wx.getStorageSync('shopId')
    }, "POST").then(res => {
      that.setData({
        cns: res.data.data,
        shijian: res.data.day,
        dianpu: res.data.shopName,
        qming: wx.getStorageSync('sign'),
        foodsafetyImg: res.data.foodsafetyImg
      })
      if (that.data.qming == '') {
        console.log(4444444444)
        that.setData({
          // qqqm: true,
          qming: ''
        })
      }
      // if (that.data.foodsafetyImg == '') {
      //   that.setData({
      //     isshw: true
      //   })

      // }
      that.downLoad()
    })
  },
  // 确定生成承诺书
  // shengcheng() {
  //   var that = this
  //   that.shengcnuoshu()

  // },
  // 生成承诺书
  shengcnuoshu() {
    wx.showLoading({
      title: '合成中...',
    })
    var that = this
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'shareCanvas' + that.data.aaa,
        success: (res) => {
          console.log('canvasToTempFilePath： ', res);
          that.data.aaa++;
          that.setData({
            aaa: that.data.aaa
          })
          var url = res.tempFilePath
          wx.uploadFile({
            url: yuming + 'Besall/Upload',
            filePath: url,
            name: 'file',
            formData: {

            },
            success(res) {
              console.log(333)
              var data = JSON.parse(res.data)
              var img = data.imgUrl
              console.log(img)
              that.setData({
                foodsafetyImg: img,
              })
              wx.hideLoading({
                success: (res) => {
                  that.tijiao()
                },
              })
            }
          })

        }
      })
    }, 1000)
  },
  tijiao() {
    var that = this
    this.myRequest(yuming + 'shop/shopSaveBossBg', {
      shopId: wx.getStorageSync('shopId'),
      foodsafetyImg: that.data.foodsafetyImg
    }, "POST").then(res => {
      if (res.data.code == 200) {
        wx.showToast({
          title: '生成成功',
          icon: 'none'
        })
        that.chengns()
      }
    })
  },
  // 重新签名
  chongxin() {
    var that = this
    this.myRequest(yuming + 'shop/shopSaveBossBg', {
      shopId: wx.getStorageSync('shopId'),
      foodsafetyImg: ''
    }, "POST").then(res => {
      wx.setStorageSync('sign', '')
      that.chengns()
      // that.qianmi()
      setTimeout(function () {
        that.setData({
          qqqm: true
        })
      }, 1000)
      // that.qianmi()
      // that.setData({
      //   qqqm:true
      // })
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      isKaoshi: false,
      finish: false,
    })
    this.getGlzdList();
    this.getDtxy();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
})